import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';

const InputContainer = WrappedComponent =>
    class InputContainer extends PureComponent {
        static propTypes = {
            onChange: PropTypes.func,
            value: PropTypes.string
        };
        constructor(props) {
            super(props);
            this.state = {
                value: this.props.value || ''
            };
            this.onNameChange = this.onNameChange.bind(this);
        }
        onNameChange(event) {
            this.setState({ value: event.target.value });
            if (this.props.onChange) {
                this.props.onChange(event, event.target.value);
            }
        }
        componentWillReceiveProps({ value }) {
            if (value) {
                this.setState({ value: value });
            }
        }
        render() {
            const newProps = {
                value: this.state.name,
                onChange: this.onNameChange
            };
            return <WrappedComponent {...this.props} {...newProps} />;
        }
    };

class Input extends PureComponent {
    static propTypes = {
        type: PropTypes.string,
        autoFocus: PropTypes.bool,
        value: PropTypes.string,
        name: PropTypes.object,
        placeholder: PropTypes.string
    };
    static defaultProps = {
        type: 'text'
    };

    clickHandle = e => {
        e.target.focus();
    };
    render() {
        const { type, autoFocus, className } = this.props;
        return (
            <div className={className}>
                {type === 'text' ? (
                    <input
                        onClick={this.clickHandle}
                        type="text"
                        placeholder={this.props.placeholder}
                        autoFocus={autoFocus}
                        {...this.props}
                    />
                ) : (
                    <textarea
                        {...this.props}
                        placeholder={this.props.placeholder}
                    >
                        {this.props.value}
                    </textarea>
                )}
            </div>
        );
    }
}
export default InputContainer(Input);
